package com.mm.cloth.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.tabs.TabLayout;
import com.mm.cloth.R;
import com.mm.cloth.adapter.TaskStatusAdapter;
import com.mm.cloth.manager.TaskStatusManager;
import com.mm.cloth.model.TaskStatus;

import java.util.List;

public class TaskStatusFragment extends Fragment implements TaskStatusManager.TaskStatusListener {
    private static final String TAG = "TaskStatusFragment";
    
    private RecyclerView rvTasks;
    private TaskStatusAdapter adapter;
    private SwipeRefreshLayout swipeRefresh;
    private TabLayout tabLayout;
    private LinearLayout tvEmptyState;
    private TextView tvEmptyStateText;
    private TextView tvProcessingCount;
    private ImageView btnBack;
    private ImageView btnClearAll;
    
    private TaskStatusManager taskManager;
    private TaskStatus.Status currentFilter = null; // null表示显示所有
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_task_status, container, false);
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);



        initViews(view);
        setupRecyclerView();
        setupTabLayout();
        setupSwipeRefresh();

        taskManager = TaskStatusManager.getInstance();
        taskManager.addListener(this);

        loadTasks();
        updateProcessingCount();
    }
    
    private void initViews(View view) {
        rvTasks = view.findViewById(R.id.rvTasks);
        swipeRefresh = view.findViewById(R.id.swipeRefresh);
        tabLayout = view.findViewById(R.id.tabLayout);
        tvEmptyState = view.findViewById(R.id.tvEmptyState);
        tvEmptyStateText = view.findViewById(R.id.tvEmptyStateText);
        tvProcessingCount = view.findViewById(R.id.tvProcessingCount);
        btnBack = view.findViewById(R.id.btnBack);
        btnClearAll = view.findViewById(R.id.btnClearAll);

        // 设置点击事件
        btnBack.setOnClickListener(v -> {
            if (getActivity() != null) {
                getActivity().onBackPressed();
            }
        });

        btnClearAll.setOnClickListener(v -> {
            taskManager.clearCompletedTasks();
            loadTasks();
            updateProcessingCount();
        });
    }
    
    private void setupRecyclerView() {
        adapter = new TaskStatusAdapter(requireContext());
        rvTasks.setLayoutManager(new LinearLayoutManager(requireContext()));
        rvTasks.setAdapter(adapter);
        
        // 设置点击监听器
        adapter.setOnTaskClickListener(task -> {
            // TODO: 打开任务详情或结果页面
            showTaskDetail(task);
        });
        
        adapter.setOnTaskDeleteListener(task -> {
            taskManager.deleteTask(task.getTaskId());
            loadTasks();
            updateProcessingCount();
        });
    }
    
    private void setupTabLayout() {
        tabLayout.addTab(tabLayout.newTab().setText("全部"));
        tabLayout.addTab(tabLayout.newTab().setText("处理中"));
        tabLayout.addTab(tabLayout.newTab().setText("已完成"));
        tabLayout.addTab(tabLayout.newTab().setText("失败"));
        
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        currentFilter = null; // 全部
                        break;
                    case 1:
                        currentFilter = TaskStatus.Status.PROCESSING;
                        break;
                    case 2:
                        currentFilter = TaskStatus.Status.COMPLETED;
                        break;
                    case 3:
                        currentFilter = TaskStatus.Status.FAILED;
                        break;
                }
                loadTasks();
            }
            
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}
            
            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }
    
    private void setupSwipeRefresh() {
        swipeRefresh.setColorSchemeColors(
            getResources().getColor(R.color.dopamine_blue),
            getResources().getColor(R.color.pink_500),
            getResources().getColor(R.color.colorAccent)
        );
        
        swipeRefresh.setOnRefreshListener(() -> {
            loadTasks();
            updateProcessingCount();
            swipeRefresh.setRefreshing(false);
        });
    }
    
    private void loadTasks() {
        List<TaskStatus> tasks;
        if (currentFilter == null) {
            tasks = taskManager.getAllTasks();
        } else {
            tasks = taskManager.getTasksByStatus(currentFilter);
        }
        
        adapter.updateTasks(tasks);
        
        // 显示空状态
        if (tasks.isEmpty()) {
            tvEmptyState.setVisibility(View.VISIBLE);
            rvTasks.setVisibility(View.GONE);

            String emptyText = getEmptyStateText();
            tvEmptyStateText.setText(emptyText);
        } else {
            tvEmptyState.setVisibility(View.GONE);
            rvTasks.setVisibility(View.VISIBLE);
        }
    }
    
    private String getEmptyStateText() {
        if (currentFilter == null) {
            return "还没有处理任务\n快去使用AI工具吧～";
        } else {
            switch (currentFilter) {
                case PROCESSING:
                    return "没有正在处理的任务";
                case COMPLETED:
                    return "还没有完成的任务";
                case FAILED:
                    return "没有失败的任务";
                default:
                    return "暂无数据";
            }
        }
    }
    
    private void updateProcessingCount() {
        int count = taskManager.getProcessingTaskCount();
        if (count > 0) {
            tvProcessingCount.setVisibility(View.VISIBLE);
            tvProcessingCount.setText("正在处理 " + count + " 个任务");
        } else {
            tvProcessingCount.setVisibility(View.GONE);
        }
    }
    
    private void showTaskDetail(TaskStatus task) {
        // TODO: 实现任务详情页面
        if (getActivity() != null) {
            // 可以启动一个详情Activity或者显示详情Dialog
        }
    }
    
    // TaskStatusManager.TaskStatusListener 实现
    @Override
    public void onTaskAdded(TaskStatus task) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                loadTasks();
                updateProcessingCount();
            });
        }
    }
    
    @Override
    public void onTaskUpdated(TaskStatus task) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                adapter.notifyTaskUpdated(task);
                updateProcessingCount();
            });
        }
    }
    
    @Override
    public void onTaskCompleted(TaskStatus task) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                loadTasks();
                updateProcessingCount();
            });
        }
    }
    
    @Override
    public void onTaskFailed(TaskStatus task) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                loadTasks();
                updateProcessingCount();
            });
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();



        if (taskManager != null) {
            taskManager.removeListener(this);
        }
    }
}
